package com.daxiong.hfs;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.daxiong.hfs.bean.CompanyBean;
import com.daxiong.hfs.bean.MainBean;
import com.daxiong.hfs.constant.Constant;
import com.daxiong.hfs.util.CommonUtil;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class ProductDetailActivity extends Activity {

	private EditText effect;

	private TextView company;

	private EditText content;

	private EditText declare;

	private EditText warnings;

	private MainBean mainBean;

	private Button companyQuery;

	private TextView chineseName;

	private EditText precautions;

	private TextView qualifiedId;

	private ProgressDialog dialog;

	private EasyTracker easyTracker;

	private void initialize() {
		easyTracker = EasyTracker.getInstance(ProductDetailActivity.this);

		mainBean = CommonUtil.getMainBeanFormIntent(getIntent());
	}

	private void last() {
		if (!mainBean.isExecution()) {
			return;
		}

		String text = StringUtils.EMPTY;

		if (CollectionUtils.isEmpty(mainBean.getCompanyResultList())) {
			text = "查無資料";
		}

		if (mainBean.getException() != null) {
			text = "無法獲取服務器的資料，請稍候執行";
		}

		if (StringUtils.isNotBlank(text)) {
			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		mainBean.setException(null);

		mainBean.setExecution(false);
	}

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.product_detail_layout);

		initialize();

		setupViews();

		last();
	}

	@Override
	public void onStart() {
		super.onStart();

		EasyTracker.getInstance(this).activityStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();

		EasyTracker.getInstance(this).activityStop(this);
	}

	private void setupViews() {
		chineseName = (TextView) findViewById(R.id.chinese_name_contents);

		qualifiedId = (TextView) findViewById(R.id.qualified_id_contents);

		company = (TextView) findViewById(R.id.company_contents);

		content = (EditText) findViewById(R.id.content_contents);

		effect = (EditText) findViewById(R.id.effect_contents);

		declare = (EditText) findViewById(R.id.declare_contents);

		warnings = (EditText) findViewById(R.id.warnings_contents);

		precautions = (EditText) findViewById(R.id.precautions_contents);

		companyQuery = (Button) findViewById(R.id.company_query);

		chineseName.setText(String.format("中文品名：%s", mainBean
				.getProductSelect().getChineseName()));

		company.setText(String.format("申請商：%s", mainBean.getProductSelect()
				.getCompany()));

		qualifiedId.setText(String.format("許可證字號：%s", mainBean
				.getProductSelect().getQualifiedId()));

		content.setText(mainBean.getProductSelect().getContent());

		effect.setText(mainBean.getProductSelect().getEffect());

		declare.setText(mainBean.getProductSelect().getDeclare());

		warnings.setText(mainBean.getProductSelect().getWarnings());

		precautions.setText(mainBean.getProductSelect().getPrecautions());

		companyQuery.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View view) {
				mainBean.setException(null);

				mainBean.setExecution(true);

				final String category = "ui_action";

				final String action = "button_press";

				final String label = "query_company";

				final MapBuilder mapBuilder = //
				MapBuilder.createEvent(category, action, label, null);

				easyTracker.send(mapBuilder.build());

				final Context context = ProductDetailActivity.this;

				final String company = mainBean.getProductSelect().getCompany();

				if (StringUtils.isBlank(company)) {
					final Toast toast = //
					Toast.makeText(context, "本筆資料未提供申請商名稱", Toast.LENGTH_LONG);

					toast.show();

					return;
				}

				dialog = //
				ProgressDialog.show(context, "資料查詢中，請稍候", "連接服務器", true);

				final AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
					@Override
					public void onFailure( //
							final int statusCode, //
							final Header[] headers, //
							final byte[] errorResponse, //
							final Throwable e //
					) {
						dialog.dismiss();

						final Toast toast = //
						Toast.makeText(context, "取得資料失敗", Toast.LENGTH_LONG);

						toast.show();
					}

					@Override
					public void onSuccess( //
							final int statusCode, //
							final Header[] headers, //
							final byte[] response //
					) {
						final String json = new String(response);

						final List<CompanyBean> companyBeanList = //
						CommonUtil.processCompanyJSON(json);

						dialog.dismiss();

						if (CollectionUtils.isEmpty(companyBeanList)) {
							final Toast toast = //
							Toast.makeText(context, "查無資料", Toast.LENGTH_LONG);

							toast.show();
						} else {
							Class<?> clazz = null;

							mainBean.setCompanyResultList(companyBeanList);

							if (companyBeanList.size() == 1) {
								final CompanyBean companySelect = //
								companyBeanList.get(0);

								mainBean.setCompanySelect(companySelect);

								clazz = CompanyDetailActivity.class;

							} else {
								clazz = CompanyResultActivity.class;
							}

							final Intent intent = new Intent(context, clazz);

							CommonUtil.putSerializable( //
									intent, //
									mainBean, //
									Constant.MAIN_BEAN_KEY //
									);

							startActivity(intent);
						}
					}
				};

				final String companyName = //
				mainBean.getProductSelect().getCompany();

				final String format = "http://140.137.207.55:8080/relay/query?companyName=%s";

				final String url = String.format(format, companyName);

				new AsyncHttpClient().get(url, responseHandler);
			}
		});
	}
}
